package com.yunji.quartz.controller;

import com.yunji.common.base.response.Response;
import com.yunji.common.base.response.ResponseHelper;
import com.yunji.common.constant.General;
import com.yunji.common.exception.job.TaskException;
import com.yunji.common.utils.StringUtils;
import com.yunji.quartz.domain.SysJob;
import com.yunji.quartz.service.ISysJobService;
import com.yunji.quartz.util.CronUtils;
import com.yunji.quartz.util.ScheduleUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 调度任务信息操作处理
 *
 * @author yunji
 */
@Api(tags = "调度任务信息操作处理")
@RestController
@RequestMapping("/monitor/job")
public class SysJobController {
    @Autowired
    private ISysJobService jobService;

    /**
     * 查询定时任务列表
     */
    @ApiOperation("查询定时任务列表")
    @PreAuthorize("@ss.hasPermi('monitor:job:list')")
    @GetMapping("/list")
    public Response<List<SysJob>> list(SysJob sysJob) {
        return ResponseHelper.successWithPage(jobService.selectJobList(sysJob));
    }

    /**
     * 导出定时任务列表
     */
    @ApiOperation("导出定时任务列表")
    @PreAuthorize("@ss.hasPermi('monitor:job:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysJob sysJob) {
//        List<SysJob> list = jobService.selectJobList(sysJob);
//        ExcelUtil<SysJob> util = new ExcelUtil<>(SysJob.class);
//        util.exportExcel(response, list, "定时任务");
    }

    /**
     * 获取定时任务详细信息
     */
    @ApiOperation("获取定时任务详细信息")
    @PreAuthorize("@ss.hasPermi('monitor:job:query')")
    @GetMapping(value = "/{jobId}")
    public Response<SysJob> getInfo(@PathVariable("jobId") Long jobId) {
        return ResponseHelper.success(jobService.selectJobById(jobId));
    }

    /**
     * 新增定时任务
     */
    @ApiOperation("新增定时任务")
    @PreAuthorize("@ss.hasPermi('monitor:job:add')")
    @PostMapping
    public Response<String> add(@RequestBody SysJob job) throws SchedulerException, TaskException {
        if (!CronUtils.isValid(job.getCronExpression())) {
            return ResponseHelper.failure("新增任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), General.LOOKUP_RMI)) {
            return ResponseHelper.failure("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{General.LOOKUP_LDAP, General.LOOKUP_LDAPS})) {
            return ResponseHelper.failure("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{General.HTTP, General.HTTPS})) {
            return ResponseHelper.failure("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), General.JOB_ERROR_STR)) {
            return ResponseHelper.failure("新增任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
            return ResponseHelper.failure("新增任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        //job.setCreateBy(SystemContext.getUsername());
        Assert.isTrue(jobService.insertJob(job) > 0, "新增失败");
        return ResponseHelper.success();
    }

    /**
     * 修改定时任务
     */
    @ApiOperation("修改定时任务")
    @PreAuthorize("@ss.hasPermi('monitor:job:edit')")
    @PutMapping
    public Response<String> edit(@RequestBody SysJob job) throws SchedulerException, TaskException {
        if (!CronUtils.isValid(job.getCronExpression())) {
            return ResponseHelper.failure("修改任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), General.LOOKUP_RMI)) {
            return ResponseHelper.failure("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{General.LOOKUP_LDAP, General.LOOKUP_LDAPS})) {
            return ResponseHelper.failure("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{General.HTTP, General.HTTPS})) {
            return ResponseHelper.failure("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), General.JOB_ERROR_STR)) {
            return ResponseHelper.failure("修改任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
            return ResponseHelper.failure("修改任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        //job.setUpdateBy(SystemContext.getUsername());
        Assert.isTrue(jobService.updateJob(job) > 0, "修改失败");
        return ResponseHelper.success();
    }

    /**
     * 定时任务状态修改
     */
    @ApiOperation("定时任务状态修改")
    @PreAuthorize("@ss.hasPermi('monitor:job:changeStatus')")
    @PutMapping("/changeStatus")
    public Response<String> changeStatus(@RequestBody SysJob job) throws SchedulerException {
        SysJob newJob = jobService.selectJobById(job.getJobId());
        newJob.setStatus(job.getStatus());
        Assert.isTrue(jobService.changeStatus(newJob) > 0, "修改失败");
        return ResponseHelper.success();
    }

    /**
     * 定时任务立即执行一次
     */
    @ApiOperation("定时任务立即执行一次")
    @PreAuthorize("@ss.hasPermi('monitor:job:changeStatus')")
    @PutMapping("/run")
    public Response<String> run(@RequestBody SysJob job) throws SchedulerException {
        boolean result = jobService.run(job);
        return result ? ResponseHelper.success() : ResponseHelper.failure("任务不存在或已过期！");
    }

    /**
     * 删除定时任务
     */
    @ApiOperation("删除定时任务")
    @PreAuthorize("@ss.hasPermi('monitor:job:remove')")
    @DeleteMapping("/{jobIds}")
    public Response<String> remove(@PathVariable Long[] jobIds) throws SchedulerException, TaskException {
        jobService.deleteJobByIds(jobIds);
        return ResponseHelper.success();
    }
}
